package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.MaterielLomContent;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import java.util.ArrayList;
import org.json.JSONException;

public class MaterielDialogFragment extends DialogFragment {

  /** 回传对象f */
  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.extra_value";
  public static final String type_catragory = "0";//类别
  public static final String type_materiel = "1";//物料名称
  private BaseVolleyActivity mActivity;

  private ArrayAdapter<MaterielLomContent> mAdapter;

  private AlertDialog mDialog;
  protected String customerId = "";//客户单位id
  protected String storageId = "";//仓库id
  protected String kindId = "";//物料类别id
  protected String type = "";//0是选择物料类别，1是选择的物料

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {

    Builder builderSingle = new AlertDialog.Builder(getActivity());
    View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_progress, null);
    builderSingle.setView(v);
    mDialog = builderSingle.create();

    return mDialog;
  }

  @Override public void onCreate(Bundle savedInstanceState) {

    mActivity = (BaseVolleyActivity) getActivity();
    customerId = (String) getArguments().getSerializable("customerId");
    storageId = (String) getArguments().getSerializable("storageId");
    kindId = (String) getArguments().getSerializable("kindId");
    type = (String) getArguments().getSerializable("type");

    volleyPost();
    super.onCreate(savedInstanceState);
  }

  private void volleyPost() {
    if (!MyUtils.isNetLink(getActivity())) {
      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MATERIE_LOM);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("dataStatus", "publish");
    if (TextUtils.isEmpty(customerId)) {
      params.put("customerId", "");
    } else {
      params.put("customerId", customerId);
    }
    if (TextUtils.isEmpty(storageId)) {
      params.put("storageId", "");
    } else {
      params.put("storageId", storageId);
    }

    //查类别
    if (type.equals(type_catragory)) {
      params.put("ifContainProduct", "false");
      params.put("ifContainKind", "true");
      params.put("ifLastKind", "true");
    }
    //查物料lom
    else if (type.equals(type_materiel)) {
      params.put("ifContainProduct", "true");
      params.put("ifContainKind", "false");
    }
    params.put("materialKindCodeLike", kindId);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        ArrayList<MaterielLomContent> list;
        list = resolveResponse(arg0);

        if (list == null || list.size() == 0) {
          emptyToast();
          mDialog.dismiss();
          return;
        }
        setAdapter(list);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  /**
   * 当列表数据为空时的自定义提示。默认提示“空数据”。
   * 重写这个方法的时候不要调用super。
   */
  protected void emptyToast() {
    Toast.makeText(getActivity(), R.string.empty_data, Toast.LENGTH_SHORT).show();
  }

  /**
   * 解析响应,将相应解析成对象后必须重新封装成CustomerDialog列表.
   *
   * @param arg0 服务器获取的json数据
   */
  public ArrayList<MaterielLomContent> resolveResponse(String arg0) {

    ArrayList<MaterielLomContent> list = new ArrayList<>();
    MaterielLomContent[] dataList = new Gson().fromJson(arg0, MaterielLomContent[].class);

    if (dataList == null || dataList.length == 0) {

      return null;
    }
    for (MaterielLomContent aDataList : dataList) {
      list.add(aDataList);
    }
    return list;
  }

  private void setAdapter(ArrayList<MaterielLomContent> customerDialogs) {
    mDialog.dismiss();

    if (mAdapter == null) {
      if (null == getActivity()) {
        return;
      }

      mAdapter = new ArrayAdapter<MaterielLomContent>(getActivity(),
          android.R.layout.select_dialog_singlechoice, customerDialogs) {

        @Override public View getView(int position, View convertView, ViewGroup parent) {
          MaterielLomContent user = getItem(position);
          if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                .inflate(android.R.layout.simple_list_item_1, parent, false);
          }
          TextView tvName = (TextView) convertView.findViewById(android.R.id.text1);

          tvName.setText(user.getName());

          return convertView;
        }
      };
    } else {
      mAdapter.clear();
      mAdapter.addAll(customerDialogs);
    }

    Builder builderSingle = new AlertDialog.Builder(getActivity());
    builderSingle.setAdapter(mAdapter, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        MaterielLomContent customerDialog = mAdapter.getItem(which);

        if (getTargetFragment() == null) return;
        Intent i = new Intent();
        i.putExtra(EXTRA_VALUE, customerDialog);
        LogUtil.i("customerDialog===" + customerDialog);
        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
      }
    });
    builderSingle.create().show();
  }
}
